var express = require('express');                                                                                                                                                                                                                                           
var router = express.Router();
var fs = require('fs');
var path = require('path');
var multer = require('multer');
var multiparty = require('multiparty');
var os = require('os');

var upload = multer({ dest: 'public/files/' });

// 单图上传
router.post('/singleUpload', upload.single('logo'), function (req, res, next) {    
  let type = req.file.mimetype;
  let  extension_name  = '';
  switch (type) {   //判断文件类型  
    case 'image/pjpeg': extension_name = '.jpg';  break;  
    case 'image/jpeg': extension_name = '.jpg'; break;  
    case 'image/gif': extension_name = '.gif'; break;  
    case 'image/png': extension_name = '.png'; break;  
    case 'image/x-png': extension_name = '.png'; break;  
    case 'image/bmp': extension_name = '.bmp'; break;   
  }  
  let realName = 'public/files/'+ req.file.filename + extension_name;
  fs.renameSync(req.file.path,realName);
  const IP = serverIP();
  const data = {
    status:0,
    url: IP+":3000/files/"+req.file.filename+".jpg"
  }
  res.json(data);
}); 
 

/* 上传页面 */
router.post('/file/admin/upload', function(req, res) {
    //生成multiparty对象，并配置上传目标路径
    var form = new multiparty.Form({uploadDir: './public/files/'});
    //上传完成后处理
    form.parse(req, function(err, fields, files) {
        if (err) {
            res.json(ErrorHandlerCode.UPLOADIMGERROE);
        } else {
            //根据ip和时间戳重新构造上传图片名字
            let timestamp = Date.parse(new Date());
            let fileName = req.ip + timestamp;
            fileName = new Buffer(fileName).toString('base64');
            let dstPath = 'public/files/'+fileName+'.jpg';
            let uploadedPath = files.image[0].path;

            //重命名为真实文件名
            fs.rename(uploadedPath, dstPath, function(err) {
                if(err){
                    res.json(ErrorHandlerCode.UPLOADIMGERROE);
                }
            });
            const IP = serverIP();
            const data = {
                status:0,
                url: IP+":3000/files/"+fileName+".jpg"
            }
            res.json(data);
        }
    });
});

function serverIP(){
        let IPv4;
        //windows上获取IP
        for(let i=0; i<os.networkInterfaces().WLAN.length; i++){  
            if(os.networkInterfaces().WLAN[i].family === 'IPv4'){  
                IPv4 = os.networkInterfaces().WLAN[i].address;  
            }  
        }
        return IPv4; 
    }


// router.get('/download', function (req, res ,next) {
//     // let fileName = 'http://192.168.199.196:3000/files/OjoxMTUwNzk2Mzg4MjAwMA==.jpg';
//     var q = req.query;  
//     if (q.type == 'jpg') {  
//         //下载图片  
//         res.download('public/files/OjoxMTUwNzk2Mzg4MjAwMA==.jpg',
//         'test.jpg',function(err){
//             if(err){
//                 res.json(err);
//             } else {
//                 res.json('下载成功');
//             }
//         });  
//     }else if (q.type == 'txt') {  
//         //下载文档  
//         res.download(`F:/testredis/public/1.txt`);  
//     }else{  
//         res.json('错误的请求');  
//     }  
// });

var request = require('request');
router.get('/download',function(req,res,next){
    var fileUrl = 'http://192.168.199.196:3000/files/OjoxMTUwNzk2Mzg4MjAwMA==.jpg';
    var filename = 'test.jpg';
    downloadFile(fileUrl,filename,function(){
        res.json('下载完毕');
    });
}) 
function downloadFile(uri,filename,callback){
    var stream = fs.createWriteStream(filename);
    request(uri).pipe(stream).on('close', callback); 
}

module.exports = router;